<template>
  <div>
    <el-dialog
      :title="status.isAdd ? '分类添加' : '分类编辑'"
      :visible.sync="status.isshow"
      @closed="closed"
    >
      {{ form }}
      <el-form :model="form">
        <el-form-item label="上级分类" label-width="120px">
          <el-select v-model="form.pid" placeholder="请选择上级分类">
            <el-option label="顶级分类" :value="0"></el-option>
            <el-option
              v-for="item in list"
              :key="item.id"
              :label="item.catename"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分类名称" label-width="120px">
          <el-input v-model="form.catename" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="图片" label-width="120px">
          <div class="my-upload">
            <h3 class="my-upload-plus">+</h3>
            <img v-if="imgUrl" class="my-upload-img" :src="imgUrl" alt="" />
            <input
              v-if="status.isshow"
              type="file"
              class="my-upload-input"
              @change="changeFile"
            />
          </div>
        </el-form-item>
        <el-form-item label="状态" label-width="120px">
          <el-switch
            v-model="form.status"
            :active-value="1"
            :inactive-value="2"
          ></el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="status.isshow = false">取 消</el-button>
        <el-button type="primary" v-if="status.isAdd" @click="con"
          >添 加</el-button
        >
        <el-button type="primary" v-else @click="updata">修 改</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { reqcateadd, reqcateinfo, reqcateedit } from "../../../http/api";
import { successAlert, errorAlert } from "../../../utils/alert";
import { mapGetters, mapActions } from "vuex";
import path from "path";

export default {
  components: {},
  props: ["status"],
  data() {
    return {
      // 图片地址初始值
      imgUrl: "",
      form: {
        pid: "",
        catename: "",
        img: "",
        status: 1,
      },
      data: [],
    };
  },
  methods: {
    ...mapActions({ reqList: "cate/reqList" }),
    //添加
    con() {
      this.checkeddata().then(() => {
        reqcateadd(this.form).then((res) => {
          if (res.data.code === 200) {
            // 弹成功
            successAlert(res.data.msg);
            // 数据清空
            this.empty();
            // 弹框消失
            this.status.isshow = false;
            // 列表刷新----------此处调用vuex的方法------------------
            this.reqList();
          }
        });
      });
    },
    //点击了编辑按钮 ，获取一条数据 赋值
    getOne(id) {
      reqcateinfo({
        id: id,
      }).then((res) => {
        if (res.data.code === 200) {
          this.form = res.data.list;
          //  补id
          this.form.id = id;
          //给图片赋值
          this.imgUrl = this.$pre + this.form.img;
        }
      });
    },
    //验空
    checkeddata() {
      return new Promise((reslove) => {
        if (this.form.pid == "") {
          errorAlert("上级分类不能为空");
          return;
        }
        if (this.form.catename == "") {
          errorAlert("分类名称不能为空");
          return;
        }
        if (this.form.img == "") {
          errorAlert("图片不能为空");
          return;
        }
        reslove();
      });
    },
    //清空
    empty() {
      this.form = {
        pid: "",
        catename: "",
        img: "",
        status: 1,
      };
      this.imgUrl = "";
    },
    //更改
    updata() {
      this.checkeddata().then(() => {
        reqcateedit(this.form).then((res) => {
          if (res.data.code == 200) {
            successAlert(res.data.msg);
            this.empty();
            this.status.isshow = false;
            this.reqList();
          }
        });
      });
    },
    // 9.弹框关闭
    closed() {
      // 如果是添加的取消，什么都不做；如果是编辑的取消，form清空
      if (!this.status.isAdd) {
        this.empty();
      }
    },
    changeFile(e) {
      // 取到照片
      console.log(e);
      let file = e.target.files[0];
      //判断大小 1M=1024KB 1KB=1024B   file.size B
      if (file.size > 2 * 1024 * 1024) {
        errorAlert("文件大小最大2M");
        return;
      }
      // 判断文件类型 file name: "2.2.2.2.2.jpeg"
      let imgArr = [".jpg", ".jpeg", ".gif", ".png"];

      // let houzhui=file.name.slice(file.name.lastIndexOf("."))
      // console.log(houzhui);
      let extname = path.extname(file.name);
      if (!imgArr.includes(extname)) {
        errorAlert("请上传正确的图片格式");
        return;
      }

      // 根据文件生成一个图片地址，赋值给imgUrl
      this.imgUrl = URL.createObjectURL(file);
      //将文件存到form.img
      this.form.img = file;
    },
  },

  mounted() {},
  computed: { ...mapGetters({ list: "cate/list" }) },
  watch: {},
};
</script>
<style scoped lang="less">
@import "../../../less/index.less";
.my-upload {
  width: 100px;
  height: 100px;
  border: 1px dashed @primary;
  position: relative;
}
.my-upload-plus {
  width: 100%;
  height: 100%;
  text-align: center;
  line-height: 100px;
}
.my-upload-input {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  cursor: pointer;
  opacity: 0;
}
.my-upload-img {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
}
</style>
